package com.ecar.api.support.util;

import java.net.URL;
import java.util.ArrayList;  
import java.util.HashMap;
import java.util.List;  
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  

import com.ecar.api.quartz.jobs.SendOrderJob;
import com.ecar.api.support.dto.GaodeLocation;
import com.ecar.api.support.dto.Geocodes;
import com.ecar.common.dto.DataBean;
import com.ecar.common.util.DataValidateUtil;
import com.ecar.common.util.HttpClientUtil;
import com.ecar.common.util.JSONUtil;
import com.ecar.common.util.StringUtil;
import com.ecar.core.common.entity.User;

/** 
 * 乘客接口 
 *  
 * @author fire 
 * 
 */  
public class UserUtil {  
	private static final Logger logger = LoggerFactory.getLogger(UserUtil.class);  

	private static String codeurl = "https://wx.hbglky.com/api/r/passenger/{userId}/id";  
	private static String codeurl2 = "https://wx.hbglky.com/api/r/ecar/{phone}/getPassengerInfo";  
	private static String codeurl3 = "https://wx.hbglky.com/api/r/ecar/{openId}/passenger/openId";  
	private static String codeurl4 = "https://wx.hbglky.com/api/r/ecar/{userId}/passenger/delete";  
	private static String codeurl5 = "https://wx.hbglky.com/api/r/ecar/{userId}/passenger/update";  
	private static String codeurl6 = "https://wx.hbglky.com/api/r/ecar/{openId}/passenger/insert";  
	
	public static User getUser(Integer userId,String token) {  
		User user = null;  
		if (userId != null && token != null) {
			try {  
				user = new User();
				String key = Redis.K.USER.to(userId);
				//当redis里有数据是继续
				if(Redis.c.exists(key)){
					String resultUser="";
					resultUser=Redis.c.get(key);
					user=JSONUtil.deserialize(resultUser, User.class);
				}else{
					String url = codeurl.replace("{userId}", userId.toString());
					String params = "?access_token=" + token; 
					String result = HttpClientUtil.httpGet(url+params);
					if(result==null){
						return null;
					}

					JSONObject jsonObject = JSONObject.fromObject(result);
					JSONObject resultJSON=null;
					if (jsonObject.containsKey("code") && jsonObject.getInt("code") == 200) {
						resultJSON=jsonObject.getJSONObject("result");
					}
					user=JSONUtil.deserialize(resultJSON, User.class);
					String a=JSONUtil.serialize(user);
					Redis.c.setex(Redis.K.USER.to(userId), Redis.DAY * 3, a);
				}

			} catch (Exception e) {  
				e.printStackTrace();  
			}  
		} 
		return user;  
	}  

	public static User getUserByPhone(String phone) {  
		User user = new User();
		if (phone != null) {
			try {  
				user = new User();
				String key = Redis.K.USER_PHONE.to(phone);
				//当redis里有数据是继续
				if(Redis.c.exists(key)){
					String resultUser="";
					resultUser=Redis.c.get(key);
					user=JSONUtil.deserialize(resultUser, User.class);
				}else{
					String url = codeurl2.replace("{phone}", phone);
					String result = HttpClientUtil.httpGet(url);
					if(result==null){
						return null;
					}

					JSONObject jsonObject = JSONObject.fromObject(result);
					JSONObject resultJSON=null;
					if (jsonObject.containsKey("code") && jsonObject.getInt("code") == 200) {
						resultJSON=jsonObject.getJSONObject("result");
						user=JSONUtil.deserialize(resultJSON, User.class);
					}
					String a=JSONUtil.serialize(user);
					Redis.c.setex(Redis.K.USER_PHONE.to(phone), Redis.M30, a);
				}

			} catch (Exception e) {  
				e.printStackTrace();  
			}  
		} 
		return user;  
	}  

	public static User getUserByOpenId(String openId) {  
		User user = null;
		if (openId != null && !openId.equals("")) {
			try {  

				String url = codeurl3.replace("{openId}", openId);
				String result = HttpClientUtil.httpGet(url);
				if(result==null){
					return null;
				}

				JSONObject jsonObject = JSONObject.fromObject(result);
				JSONObject resultJSON=null;
				if (jsonObject.containsKey("code") && jsonObject.getInt("code") == 404) {
					user = new User();
					resultJSON=jsonObject.getJSONObject("result");
					user=JSONUtil.deserialize(resultJSON, User.class);
				}else{
					System.out.println(jsonObject.getInt("code"));
				}
			} catch (Exception e) {  
				e.printStackTrace();  
			}  
		} 
		return user;  
	}  

	/**
	 * 
            "id":346,  必填
            "phone ":"137xxxxxxxx",
            " name ":"张三",
            "idcard ":"421081xxxxxx",
            "gender ":0,
            "openid ":"123adad",
            "unionid ":"adf134"
	 * 
	 * @param user
	 * @return
	 */
	
	public static int updateUserByUserId(User user) {  
		int i = -1;  
		if (user != null && !user.getId().equals("")) {
			try {  
				String url = codeurl5.replace("{userId}", user.getId()+"");
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("fields", DataValidateUtil.parseNull(user));
				Map<String, Object> tempMap=new HashMap<String, Object>();
				tempMap.put("param", map);
				String params = JSONUtil.serialize(tempMap);  
				String result = HttpClientUtil.httpPostContent(url, params);
				if(result==null){
					return 0;
				}

				JSONObject jsonObject = JSONObject.fromObject(result);
				if (jsonObject.containsKey("code") && jsonObject.getInt("code") == 200) {
					return 1;
				}
			} catch (Exception e) {  
				e.printStackTrace();  
			}  
		} 
		return i;  
	}

	
	/**
	 *  "phone ":"137xxxxxxxx", 必填
            " name ":"张三",
            "idcard ":"421081xxxxxx",
            "gender ":0,
            "openid ":"123adad",
            "unionid ":"adf134"
	 * @param user
	 * @return
	 */
	public static int insertUserByOpenId(User user) {  
		int i = -1;  
		if (user != null && !user.getOpenid().equals("")) {
			try {  
				String url = codeurl6.replace("{openId}", user.getOpenid());
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("fields", user);
				Map<String, Object> tempMap=new HashMap<String, Object>();
				tempMap.put("param", map);
				String params = JSONUtil.serialize(tempMap);  
				System.out.println(params);
				String result = HttpClientUtil.httpPostContent(url, params);
				if(result==null){
					return 0;
				}

				JSONObject jsonObject = JSONObject.fromObject(result);
				if (jsonObject.containsKey("code") && jsonObject.getInt("code") == 200) {
					return 1;
				}
			} catch (Exception e) {  
				e.printStackTrace();  
			}  
		} 
		return i; 
	}

	public static int deleteUserByUserId(Integer userId) {  
		int i = -1;  
		if (userId != null) {
			try {  
				String url = codeurl4.replace("{userId}", userId+"");
				String result = HttpClientUtil.httpGet(url);
				if(result==null){
					return 0;
				}

				JSONObject jsonObject = JSONObject.fromObject(result);
				if (jsonObject.containsKey("code") && jsonObject.getInt("code") == 200) {
					return 1;
				}
			} catch (Exception e) {  
				e.printStackTrace();  
			}  
		} 
		return i; 
	}

}  